package com.asktgapp.user.fragment;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.dialog.BindAccountDialog;
import com.asktgapp.hxsg.BiuEaseHelper;
import com.asktgapp.model.LoginVO;
import com.asktgapp.receiver.SoundService;
import com.asktgapp.user.activity.BindAccountActivity;
import com.asktgapp.user.activity.FindPwdActivity;
import com.asktgapp.user.activity.MainActivity;
import com.asktgapp.user.activity.RegisterNowActivity;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.sobot.chat.utils.ToastUtil;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/4
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description: 登录fragment
 */

public class LoginFragment extends BaseFragment {
    @InjectView(R.id.et_name)
    EditText mNameEt;
    @InjectView(R.id.et_password)
    EditText mPassWordEt;
    @InjectView(R.id.tv_forget)
    TextView mForgetTv;
    @InjectView(R.id.iv_eye)
    ImageView mEye;
    @InjectView(R.id.tv_login)
    TextView mLogin;
    @InjectView(R.id.iv_wx)
    ImageView mWx;
    @InjectView(R.id.iv_qq)
    ImageView mQQ;
    @InjectView(R.id.laterLogin)
    TextView laterLogin;
    private boolean isHide = true;
    private int reload;
    private LoginVO bean;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_login, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        reload = getActivity().getIntent().getIntExtra("reload", 0);
        mEye.setOnClickListener(this);
        mForgetTv.setOnClickListener(this);
        mLogin.setOnClickListener(this);
        mWx.setOnClickListener(this);
        mQQ.setOnClickListener(this);
        laterLogin.setOnClickListener(this);
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(getActivity()).setShareConfig(config);
    }

    @Override
    public void loadData() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_eye:
                String pwd = mPassWordEt.getText().toString().trim();
                if (!Util.isEmpty(pwd)) {
                    if (isHide) {
                        mPassWordEt.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        mEye.setImageResource(R.mipmap.ico_zhengyan);
                    } else {
                        mPassWordEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        mEye.setImageResource(R.mipmap.ico_biiyan);
                    }
                    mPassWordEt.setSelection(pwd.length());
                    isHide = !isHide;
                }
                break;
            case R.id.tv_forget:
                startActivity(new Intent(getActivity(), FindPwdActivity.class));
                break;
            case R.id.tv_login:

                String name = mNameEt.getText().toString().trim();
                String password = mPassWordEt.getText().toString().trim();
                if (Util.isEmpty(name)) {
                    showTost("请输入手机号", 0);
                    return;
                }
                if (Util.isEmpty(password)) {
                    showTost("请输入密码", 0);
                    return;
                }
                doLogin(name, password);
                break;
            case R.id.iv_wx:
                doWXlogin();
                break;
            case R.id.iv_qq:
                doQQLogin();
                break;

            case R.id.laterLogin:
                Log.i("type", "是否是重新登录= 不是，打开到MainA");
                startActivity(new Intent(getActivity(), MainActivity.class));
                getActivity().finish();
                break;
        }
    }

    private void doQQLogin() {
        getPer();
        MyApplication.ShareAPI.getPlatformInfo(getActivity(), SHARE_MEDIA.QQ, authListener);
    }

    private void doWXlogin() {
        getPer();
//        if (!MyApplication.mWxApi.isWXAppInstalled()) {
//            showTost("您还未安装微信客户端", 0);
//            return;
//        }
//        final SendAuth.Req req = new SendAuth.Req();
//        req.scope = "snsapi_userinfo";
//        req.state = "jg_wx_login";
//        MyApplication.mWxApi.sendReq(req);
        MyApplication.ShareAPI.getPlatformInfo(getActivity(), SHARE_MEDIA.WEIXIN, authListener);
    }

    private void doLogin(String name, String pwd) {
        HashMap params = new HashMap();
        params.put("type", 0);
        params.put("phone", name);
        params.put("password", Util.encodeMD5(pwd));
        if (!Utils.noContainsEmoji(name, pwd)) {
            showTost("不能输入emoji表情", 0);
            return;
        }
        Apiservice apiservice = ApiUtil.getInstance().create();
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody<LoginVO>> call = apiservice.Login(params);
        call.enqueue(new Callback<ApiResponseBody<LoginVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<LoginVO>> call, Response<ApiResponseBody<LoginVO>> response) {
                if (response.isSuccessful()) {

                    Log.i("login", "登录成功！");
                    bean = response.body().getResult();
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_HX_ID, bean.getHuanxinId());
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.USER_ID, bean.getId());
                    PreferencesUtil.putInt(getActivity(), PreferencesUtil.IS_SHOW_AUTH_DOOR, bean.getIsShow());
                    if (bean.getIsEngineer() == 1) {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER, true);
                        PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_NAME, bean.getRealname() + "");
                    } else {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER, false);
                        PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_NAME, bean.getUsername() + "");
                    }
                    // PreferencesUtil.putInt(getActivity(), PreferencesUtil.KEY_IS_ENGINEER, bean.getIsEngineer());
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.HEAD_IMG, bean.getUserPic());
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_PHONE, bean.getPhone());

                    Log.i("userid", bean.getId());
                    upToken();
                    BiuEaseHelper.loginIn();

                } else {
                    showTost(response.raw().message(), 0);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<LoginVO>> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.getErrorCode() == 1023) {
                    showTost("您已被封号，暂时不能登录！", 1);
                } else
                    showTost(apiException.getMessage(), 0);
            }
        });


    }

    private void doOtherLogin(int type, String openid, String username, String pic) {
        showProgress(getClass().getSimpleName());
        HashMap params = new HashMap();
        params.put("type", String.valueOf(type));
        if (type == 1) {
            params.put("openid", openid);
        } else {
            params.put("code", openid);
        }
        params.put("username", username);
        params.put("user_pic", pic);
        Apiservice apiservice = ApiUtil.getInstance().create();
        Call<ApiResponseBody<LoginVO>> call = apiservice.Login(params);
        call.enqueue(new Callback<ApiResponseBody<LoginVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<LoginVO>> call, Response<ApiResponseBody<LoginVO>> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    Log.i("login", "登录成功！");
                    bean = response.body().getResult();
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_HX_ID, bean.getHuanxinId());
                    PreferencesUtil.putInt(getActivity(), PreferencesUtil.IS_SHOW_AUTH_DOOR, bean.getIsShow());
                    if (bean.getIsEngineer() == 1) {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER, true);
                        PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_NAME, bean.getRealname() + "");

                    } else {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER, false);
                        PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_NAME, bean.getUsername() + "");

                    }
                    //PreferencesUtil.putInt(getActivity(), PreferencesUtil.KEY_IS_ENGINEER, bean.getIsEngineer());
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.HEAD_IMG, bean.getUserPic());
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_PASSWORD, bean.getPassword());
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_PHONE, bean.getPhone());
                    Log.i("login", "userid:" + bean.getId());
                    BiuEaseHelper.loginIn();
                    if (response.body().getKey() == 10001) {
                        upTokenWithOutSkip();
                        BindAccountDialog bindAccountDialog = new BindAccountDialog(new BindAccountDialog.onResultCallBack() {
                            @Override
                            public void onBind() {
                                onBindAccount();

                            }

                            @Override
                            public void onRegister() {
                                doRigister();

                            }
                        });
                        bindAccountDialog.show(getFragmentManager(), "BindAccountDialog");
                    } else {
                        upToken();
                    }


                } else {
                    showTost(response.raw().message(), 0);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<LoginVO>> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.getErrorCode() == 1023) {
                    showTost("您已被封号，暂时不能登录！", 1);
                } else
                    showTost(apiException.getMessage(), 0);
            }
        });


    }

    private void doRigister() {
        Intent intent = new Intent(getActivity(), RegisterNowActivity.class);
        intent.putExtra("userid", bean.getId());
        startActivity(intent);
    }

    private void onBindAccount() {
        Intent intent = new Intent(getActivity(), BindAccountActivity.class);
        intent.putExtra("userid", bean.getId());
        startActivity(intent);
        getActivity().finish();
    }

    private void upToken() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        if(bean==null||TextUtils.isEmpty(bean.getId())){
            ToastUtil.showToast(getContext(),"登录失败");
            return;
        }
        params.put("userid", bean.getId());
        params.put("ymToken", MyApplication.UmengToken);
        Log.e("UmengToken",MyApplication.UmengToken+"");
        Call<ApiResponseBody> call = apiservice.updatePushToken(params);
        call.enqueue(new Callback<ApiResponseBody>() {
                         @Override
                         public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                             dismissProgress();
                             if (response.isSuccessful()) {
                                 Log.i("login", "token上传成功！");
                                 if (reload == 1) {
                                     PreferencesUtil.putString(getActivity(), PreferencesUtil.USER_ID, bean.getId());
                                     Log.i("type", "是否是重新登录= 是");
                                     getActivity().finish();
                                 } else {
                                     PreferencesUtil.putString(getActivity(), PreferencesUtil.USER_ID, bean.getId());
                                     Log.i("type", "是否是重新登录= 不是，打开到MainA");
                                     startActivity(new Intent(getActivity(), MainActivity.class));
                                     getActivity().finish();
                                 }
                             } else {
                                 showTost(response.raw().message(), 0);
                             }
                         }

                         @Override
                         public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                             dismissProgress();
                             ApiException apiException = ExceptionHandle.handleException(t);
                             if (apiException.getErrorCode() == 1023) {
                                 showTost("您已被封号，暂时不能登录！", 1);
                             } else
                                 showTost(apiException.getMessage(), 0);
                             Log.i("login", "token上传失败！");
                         }
                     }
        );

    }

    private void upTokenWithOutSkip() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", bean.getId());
        params.put("ymToken", MyApplication.UmengToken);
        Call<ApiResponseBody> call = apiservice.updatePushToken(params);
        call.enqueue(new Callback<ApiResponseBody>() {
                         @Override
                         public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                             if (response.isSuccessful()) {
                                 Log.i("login", "  upTokenWithOutSkip  token上传成功！");
                             } else {
                                 showTost(response.raw().message(), 0);
                             }
                         }

                         @Override
                         public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                             Log.i("login", "upTokenWithOutSkip token上传失败！");
                         }
                     }
        );

    }

    public void getPer() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(getActivity(), mPermissionList, 123);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
//            Toast.makeText(getActivity(), "正在跳转...", Toast.LENGTH_LONG).show();
            showProgress(getClass().getSimpleName());
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            dismissProgress();
//            Toast.makeText(getActivity(), "成功了", Toast.LENGTH_LONG).show();
            if (platform == SHARE_MEDIA.QQ) {
                Log.i("wx_qq", data.get("openid"));
                Log.i("wx_qq", data.toString());
                doOtherLogin(1, data.get("openid"), data.get("name"), data.get("iconurl"));
            }
            if (platform == SHARE_MEDIA.WEIXIN) {
//                showTost(data.toString(), 1);
                Log.i("wx_wx", data.get("openid"));
                Log.i("wx_wx", data.toString());
                doOtherLogin(2, data.get("openid"), data.get("name"), data.get("iconurl"));
            }

        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            dismissProgress();
            Toast.makeText(getActivity(), "失败：" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            dismissProgress();
            Toast.makeText(getActivity(), "取消了授权", Toast.LENGTH_LONG).show();
        }
    };

}
